package brc.syntacticTree;

import java.io.IOException;
import java.io.Writer;

public class AssignmentNode implements TreeNode {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3252920965626418710L;
	private VariableRefenceNode variable;
	private TypedTreeNode value;
	
	public AssignmentNode(VariableRefenceNode variable, TypedTreeNode value) {
		if (variable == null || value == null) {
			throw new NullPointerException("Varname and value must be passed as parameter");
		}
		this.variable = variable;
		this.value = value;
	}
	
	public VariableRefenceNode getVariable() {
		return this.variable;
	}
	public TypedTreeNode getValue() {
		return this.value;
	}

	@Override
	public void writeAssembly(Writer writer) throws IOException {
		this.value.writeAssembly(writer);
		String cmd;
		if (value.getType() == TypedTreeNode.TIPO_TEXTO) {
			cmd = "astore ";
		}
		else {
			cmd = "istore ";
		}
		writer.write(cmd + this.variable.getReference() + "\r\n");
	}
	@Override
	public void semanticCheck() throws SemanticException {
		this.variable.setReferenced();
		this.variable.semanticCheck();		
		this.value.semanticCheck();
		
		if (this.variable.getType() != this.value.getType()) {
			throw new SemanticException("Type mismatch on " + this.variable.getVarName() + " symbol assignment");	
		}
	}
}
